package com.sy.springboottest.action.start;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import com.sy.springboottest.action.demo1.Produce;
import com.sy.springboottest.pojo.QueryPojo;
import com.sy.springboottest.pojo.QueryProtoOuterClass;
import com.sy.springboottest.pojo.ResultPojo;
import com.sy.springboottest.pojo.ResultProtoOuterClass;

//服务端启动
public class ServerStart {
	
	public  void start1() {
		int port = 8080;
		try(ServerSocket server = new ServerSocket(port)){
			while(true) {
				Socket client = server.accept();
				try {
//					InputStream inputStream = client.getInputStream();
//					ObjectInputStream objIs = new ObjectInputStream(inputStream);
//					QueryPojo queryPojo = (QueryPojo) objIs.readObject();
//					
//					OutputStream outputStream = client.getOutputStream();
//					ObjectOutputStream oos = new ObjectOutputStream(outputStream);
//					ServerStart serverStart = new ServerStart();
//					ResultPojo result = serverStart.getResult(queryPojo);
//					System.out.println(JSON.toJSONString(queryPojo));
//					// 对象输出
//					oos.writeObject(result);
//					oos.flush();
//					outputStream.flush();
					
					QueryProtoOuterClass.QueryProto qp = QueryProtoOuterClass.QueryProto.parseFrom(client.getInputStream());
					System.out.println(String.format("first=%d;second=%d", qp.getFirst(),qp.getSecond()));
					ResultProtoOuterClass.ResultProto rp = ResultProtoOuterClass.ResultProto.newBuilder().setSum(qp.getFirst()+qp.getSecond()).build();
					rp.writeTo(client.getOutputStream());
					client.shutdownOutput();
				} catch (Exception e) {
					System.out.println(e.getMessage());
					e.printStackTrace();
				}
			}
		} catch (IOException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
	}
	
	
	public ResultPojo getResult(QueryPojo queryPojo) {
		Produce pro = new Produce();
		return pro.sum(queryPojo);
	}
	
	public static void main(String[] args) {
		ServerStart ss = new ServerStart();
		ss.start1();
	}
}
